package com.stoneframe.appserver.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.stoneframe.appserver.service.LoginService;
import com.stoneframe.base.cache.CacheManager;
import com.stoneframe.base.controller.BaseController;
import com.stoneframe.base.util.AppHelper;
import com.stoneframe.base.util.DateHelper;
import com.stoneframe.base.util.GuidHelper;
import com.stoneframe.base.util.PageData;
import com.stoneframe.base.util.ToolHelper;


@Controller
public class LoginController extends BaseController {
	
	private String controllerName="LoginController.";
	
	@Resource(name="loginService")
	private LoginService loginService;
	
	/**
	 * 登录 
	 */
	@RequestMapping(value="login_login",produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object login() throws Exception{
		logBefore(logger, controllerName+"login");

		PageData pd=this.getPageData();
		String userName=pd.getString("userName");
		String userPwd=pd.getString("userPwd");
		if(ToolHelper.isEmpty(userName)){
			return AppHelper.errorObject("用户名不能为空");
		}
		if(ToolHelper.isEmpty(userPwd)){
			return AppHelper.errorObject("密码不能为空");
		}
		try{
			String passwd=new SimpleHash("SHA-1",userName,userPwd).toString();
			pd.put("userPwd", passwd);
			PageData userData=loginService.getUserByNameAndPwd(pd);
			if(null!=userData){
				pd.put("lastLogin", DateHelper.getTime().toString());
				pd.put("lastAddress",getRemoteAddress());
				loginService.updateLastLogin(pd);
				
				String clientToken=GuidHelper.get32Uuid();
	            CacheManager.putCache(clientToken, userData);
				logAfter(logger);
				return AppHelper.successObject(clientToken);
			}else{
				return AppHelper.errorObject("用户名或密码错误");
			}
		}catch(AuthenticationException e){
			return AppHelper.errorObject(e.getMessage());
		}
	}
	
	/**
	 * 获取登录用户的IP 
	 */
	private String getRemoteAddress(){
		String address="";
		try{
			HttpServletRequest request=this.getRequest();
			if(request.getHeader("x-forwarded-for")==null){
				address=request.getRemoteAddr();
			}else{
				address=request.getHeader("x-forwarded-for");
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}
		return address;
	}
	
	/**
	 * 注销
	 */
	@RequestMapping(value="logout")
	@ResponseBody
	public Object logout(){
		logBefore(logger, controllerName+"logout");
		PageData pd=this.getPageData();
		CacheManager.clearAll(pd.getString("token"));
		logAfter(logger);
		return AppHelper.successObject("注销成功");
	}
	
	/**
	 * 获取当前用户信息
	 */
	@RequestMapping(value="getUserInfo")
	@ResponseBody
	public Object getUserInfo(){
		logBefore(logger, controllerName+"getCurrentUser");
		
		PageData pd=this.getPageData();
		Map<String,Object> map=new HashMap();
		map.put("userInfo", this.getCurrentUser(pd.getString("token")));
		map.put("result", "0");
		map.put("msg", "获取成功");
		
		logAfter(logger);
		return AppHelper.returnObject(pd, map);
	}

	
}
